package com.ztx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztx.pojo.Role;
import com.ztx.pojo.User;
import com.ztx.pojo.UserRole;
import com.ztx.pojo.dto.UserDto;
import com.ztx.service.RoleService;
import com.ztx.service.UserRoleService;
import com.ztx.service.UserService;
import com.ztx.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ztx
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2023-10-25 19:22:37
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleService roleService;

    @Override
    public User login(String username, String password) {
        User user = userMapper.login(username, password);

        // 更新登陆时间
        if (user != null) {
            user.setLastloginTime(new Date());
            userMapper.updateById(user);
        }

        return user;
    }

    @Override
    public User getInfo(Long userId) {
        return userMapper.selectById(userId);
    }

    // 新增用户，同时维护用户角色表
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveWithRoles(UserDto userDto) {
        this.save(userDto);

        List<Role> roles = userDto.getRoles();

        List<UserRole> userRoles = new ArrayList<>(roles.size());

        roles.forEach(role -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(userDto.getUserId());
            userRole.setRoleId(role.getRoleId());
            userRoles.add(userRole);
        });

        userRoleService.saveBatch(userRoles);
    }

    // 查询用户列表
    @Override
    public List<UserDto> listUserDto() {

        List<User> users = this.list();

        List<UserDto> userDtos = new ArrayList<>(users.size());
        users.forEach(user -> {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            // 查询userId下的role
            // 查询所有的roleId
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRole::getUserId, user.getUserId());
            List<UserRole> userRoles = userRoleService.list(queryWrapper);
            if (!userRoles.isEmpty()) {
                // 所有的roleId
                List<Long> roleIds = new ArrayList<>(userRoles.size());
                userRoles.forEach(userRole -> {
                    roleIds.add(userRole.getRoleId());
                });

                LambdaQueryWrapper<Role> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.in(Role::getRoleId, roleIds);
                List<Role> roles = roleService.list(queryWrapper1);
                userDto.setRoles(roles);
            }

            userDtos.add(userDto);
        });

        return userDtos;
    }

    // 根据用户id删除数据
    @Transactional
    @Override
    public void deleteWithRoles(Long id) {
        this.removeById(id);
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,id);
        userRoleService.remove(queryWrapper);
    }

    @Override
    public UserDto getByIdWithRoles(Long userId) {
        UserDto userDto = new UserDto();
        User user = this.getById(userId);
        BeanUtils.copyProperties(user,userDto);
        // List<Role>
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,userId);
        List<UserRole> userRoles = userRoleService.list(queryWrapper);
        if(!userRoles.isEmpty()){
            List<Long> roleIds = new ArrayList<>(userRoles.size());
            userRoles.forEach(userRole -> {
                roleIds.add(userRole.getRoleId());
            });

            LambdaQueryWrapper<Role> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.in(Role::getRoleId, roleIds);
            List<Role> roles = roleService.list(queryWrapper1);
            userDto.setRoles(roles);
        }

        return userDto;
    }

    @Transactional
    @Override
    public void updateWithRoles(UserDto userDto) {
        this.updateById(userDto);
        // 删掉
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,userDto.getUserId());
        userRoleService.remove(queryWrapper);

        // 新增的
        List<Role> roles = userDto.getRoles();
        List<UserRole> userRoles = new ArrayList<>(roles.size());
        roles.forEach(role -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(userDto.getUserId());
            userRole.setRoleId(role.getRoleId());
            userRoles.add(userRole);
        });
        userRoleService.saveBatch(userRoles);

    }
}